import config from "../common/config";

let baseUrl = config.API_URL;
let urls;
let queryString;
let second = 2000; // 2秒内同一个请求只能调用一次

// 修改点1：缓存键改为包含URL和params的哈希值
const cache = new Map();

// 生成缓存键（URL + 序列化后的params）
function getCacheKey(url, params) {
  const sortedParams = params
    ? Object.keys(params)
        .sort()
        .map((key) => `${key}=${params[key]}`)
        .join("&")
    : "";
  return `${url}?${sortedParams}`;
}

function request(method, url, params) {
  let options = {
    method,
    headers: { "Content-Type": "application/json" },
  };

  switch (true) {
    case method === "POST":
      urls = baseUrl + url;
      options.body = JSON.stringify(params);
      break; // 修复点：添加break语句
    case method === "GET":
      queryString = params
        ? Object.keys(params)
            .map((key) => `${key}=${params[key]}`)
            .join("&")
        : "";
      urls = params ? baseUrl + url + "?" + queryString : baseUrl + url;
      break; // 修复点：添加break语句
    default:
      console.log("请求失败");
  }

  const nowTime = Date.now();
  const cacheKey = getCacheKey(url, params); // 修改点2：使用新的缓存键

  // 检查缓存
  if (cache.has(cacheKey)) {
    const { promise, timestamp } = cache.get(cacheKey);
    const timeElapsed = nowTime - timestamp;

    if (timeElapsed < second) {
      return promise;
    }
    cache.delete(cacheKey);
  }

  // 发起新请求
  let data = fetchData(urls, options);
  cache.set(cacheKey, { promise: data, timestamp: nowTime });

  setTimeout(() => {
    cache.delete(cacheKey);
  }, second);

  return data;
}

function fetchData(url, params) {
  return new Promise((resolve, reject) => {
    fetch(url, params)
      .then((res) => res.json())
      .then((data) => {
        if (data.code === 200) {
          // 修复点：使用严格相等
          resolve(data);
        } else {
          reject(data);
        }
      })
      .catch((err) => reject(err));
  });
}

export default {
  get: (url, params = {}) => request("GET", url, params),
  post: (url, params = {}) => request("POST", url, params),
};
